package com.example.controller;

import com.example.common.utils.ApiResult;
import com.example.config.mybatisplusconfig.MybatisPlusCodeConfig;
import com.example.service.CodeGenerationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/codeGeneration")
public class CodeGenerationController {

    @Value("${spring.datasource.url:}")
    private String dataBaseUrl;

    @Autowired
    private CodeGenerationService codeGenerationService;

    @Autowired
    private MybatisPlusCodeConfig mybatisPlusCodeConfig;

    @RequestMapping("/index")
    public String index(ModelMap map){
        String dataBaseName = getModelName();
        if(StringUtils.isBlank(dataBaseName)){
            System.out.println("数据库不存在");
        }
        //查询数据库所有表名
        List<String> list = codeGenerationService.getAllTableName();
        map.addAttribute("tableList",list);
        map.addAttribute("dataBaseName",dataBaseName);
        return "index";
    }

    @ResponseBody
    @RequestMapping("/downloadCodeFile")
    public ApiResult<String> downloadCodeFile(String tableName){
       if(StringUtils.isBlank(tableName)){
           return new ApiResult<>(999,"表名不能为空");
       }
       String filePath =  mybatisPlusCodeConfig.codeGenerator("", tableName);
        return new ApiResult<>(filePath);
    }

    /*
    * 获取数据库名
    * */
    public String getModelName(){
        //查询数据库所有表名
        String dataBaseName = "";
        //jdbc:mysql://10.20.50.207:3306/materials?useUnicode=true&useJDBC....
        String regex = "/(\\w+)\\?";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(dataBaseUrl);
        if(m.find()){
            dataBaseName = m.group(0);
            //  dataBaseName====  /materials?
            dataBaseName= dataBaseName.replace("/","");
            dataBaseName =dataBaseName.replace("?","");
        }else{
            System.out.println("数据库不存在");
        }
        return dataBaseName;
    }
}
